/**
 * 
 */
package com.wubo.sec.web.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import com.wubo.common.util.Assert;
import com.wubo.sec.SecurityManager;
import com.wubo.sec.core.UserData;
import com.wubo.sec.core.UserLoginPageHelper;
import com.wubo.sec.event.PasswordChangeEvent;
import com.wubo.sec.service.IUserService;

/**
 * @author WuBo
 * @CreateDate 2010-9-9
 * @version 1.0.01
 */
@Controller
public class UserConfigAction extends BaseSecAction {
	@Autowired
	private IUserService userService;

	private String oldpwd;
	
	private String newpwd;
	
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public String getOldpwd() {
		return oldpwd;
	}

	public void setOldpwd(String oldpwd) {
		this.oldpwd = oldpwd;
	}

	public String getNewpwd() {
		return newpwd;
	}

	public void setNewpwd(String newpwd) {
		this.newpwd = newpwd;
	}
	
	public String changePassword(){
		try{
			if(StringUtils.hasText(oldpwd) && StringUtils.hasText(newpwd)){
				
				UserData user = SecurityManager.getCurrentUser();
				Assert.notNull(user);
				
				String password = SecurityManager.encodePassword(oldpwd, user.getUsername());
				if(password.equals(user.getPassword())){
					if(! oldpwd.equals(newpwd)){
						SecurityManager.publishEvent(new PasswordChangeEvent(user, newpwd));
					}
					jsonSuccess(null);
				}else{
					jsonError("对不起，您输入的密码不对");
				}
			}else{
				jsonError("对不起，密码或新密码不能为空");
			}
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}
	
	public String toScriptLogin(){
		String loginPage = UserLoginPageHelper.getLoginPageUrl(getHttpServletRequest());
		/*int pathIdx = loginPage.lastIndexOf("/");
		if(pathIdx != -1){
			loginPage = loginPage.substring(pathIdx+1);
		}
		int idx = loginPage.indexOf(".");
		if(idx == -1){
			idx = loginPage.length();
		}
		return loginPage.substring(pathIdx, idx);*/

		getHttpServletResponse().setHeader("ResultType", UserLoginPageHelper.SCRIPT_REQUIRED_LOGIN_JSON_RESULT);
		json(loginPage);
		return null;
	}
	
}
